"""Agent工厂 - 创建和管理不同类型的Agent"""

from typing import Dict, Any, Optional
from sqlalchemy.orm import Session
import logging

from ..agents.base import BaseAgent
from ..agents.psychological_agent import PsychologicalAgent

logger = logging.getLogger(__name__)


class AgentFactory:
    """Agent工厂类"""
    
    _agents: Dict[str, type] = {
        "psychological": PsychologicalAgent,
    }
    
    @classmethod
    def create_agent(cls, agent_type: str, db_session: Session, **kwargs) -> BaseAgent:
        """创建Agent实例"""
        if agent_type not in cls._agents:
            raise ValueError(f"不支持的Agent类型: {agent_type}")
        
        agent_class = cls._agents[agent_type]
        
        try:
            agent = agent_class(db_session, **kwargs)
            logger.info(f"成功创建 {agent_type} Agent: {agent.name}")
            return agent
            
        except Exception as e:
            logger.error(f"创建 {agent_type} Agent失败: {e}")
            raise
    
    @classmethod
    def get_available_agents(cls) -> Dict[str, str]:
        """获取可用的Agent类型"""
        return {
            agent_type: agent_class.__doc__ or f"{agent_type} Agent"
            for agent_type, agent_class in cls._agents.items()
        }
    
    @classmethod
    def register_agent(cls, agent_type: str, agent_class: type):
        """注册新的Agent类型"""
        if not issubclass(agent_class, BaseAgent):
            raise ValueError("Agent类必须继承自BaseAgent")
        
        cls._agents[agent_type] = agent_class
        logger.info(f"注册新的Agent类型: {agent_type}")


# 全局Agent实例管理器
class AgentManager:
    """Agent实例管理器"""
    
    def __init__(self):
        self._instances: Dict[str, BaseAgent] = {}
    
    def get_or_create_agent(self, agent_type: str, db_session: Session, **kwargs) -> BaseAgent:
        """获取或创建Agent实例"""
        instance_key = f"{agent_type}_{id(db_session)}"
        
        if instance_key not in self._instances:
            self._instances[instance_key] = AgentFactory.create_agent(
                agent_type, db_session, **kwargs
            )
        
        return self._instances[instance_key]
    
    def remove_agent(self, agent_type: str, db_session: Session):
        """移除Agent实例"""
        instance_key = f"{agent_type}_{id(db_session)}"
        if instance_key in self._instances:
            del self._instances[instance_key]
            logger.info(f"移除Agent实例: {instance_key}")
    
    def get_all_agents(self) -> Dict[str, BaseAgent]:
        """获取所有Agent实例"""
        return self._instances.copy()
    
    def clear_all(self):
        """清除所有Agent实例"""
        self._instances.clear()
        logger.info("清除所有Agent实例")


# 全局Agent管理器实例
agent_manager = AgentManager()
